package com.qy.controller;

import com.qy.entity.Order;
import com.qy.result.Result;
import com.qy.result.ResultUtils;
import com.qy.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@Slf4j
@RequestMapping("/taocan/order")
@RestController
@RequiredArgsConstructor
public class OrderController {
    
    private final IOrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Result<Order> createOrder(@RequestBody Order order) {
        try {
            log.info("创建订单请求: {}", order);
            Order createdOrder = orderService.createOrder(order);
            return ResultUtils.success(createdOrder);
        } catch (Exception e) {
            log.error("创建订单失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "创建订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{orderId}")
    public Result<Order> getOrderDetail(@PathVariable String orderId) {
        try {
            log.info("获取订单详情: {}", orderId);
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ResultUtils.error(404, "订单不存在");
            }
            return ResultUtils.success(order);
        } catch (Exception e) {
            log.error("获取订单详情失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "获取订单详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID获取订单列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<Order>> getOrdersByUserId(@PathVariable String userId) {
        try {
            log.info("获取用户订单列表: {}", userId);
            List<Order> orders = orderService.getOrdersByUserId(userId);
            return ResultUtils.success(orders);
        } catch (Exception e) {
            log.error("获取用户订单列表失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "获取用户订单列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有订单列表（分页）
     */
    @GetMapping("/list")
    public Result<List<Order>> getOrderList(
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        try {
            log.info("获取订单列表请求，订单ID: {}, 用户ID: {}, 状态: {}, 开始日期: {}, 结束日期: {}", 
                    orderId, userId, status, startDate, endDate);
            
            Map<String, Object> params = new HashMap<>();
            params.put("orderId", orderId);
            params.put("userId", userId);
            params.put("status", status);
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            List<Order> orders = orderService.queryOrdersByCondition(params);
            return ResultUtils.success(orders);
        } catch (Exception e) {
            log.error("获取订单列表失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "获取订单列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/{orderId}/pay")
    public Result<Boolean> payOrder(@PathVariable String orderId) {
        try {
            log.info("支付订单请求: {}", orderId);
            boolean result = orderService.payOrder(orderId);
            if (result) {
                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(500, "支付订单失败");
            }
        } catch (Exception e) {
            log.error("支付订单失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "支付订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/{orderId}/cancel")
    public Result<Boolean> cancelOrder(@PathVariable String orderId) {
        try {
            log.info("取消订单请求: {}", orderId);
            boolean result = orderService.cancelOrder(orderId);
            if (result) {
                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(500, "取消订单失败");
            }
        } catch (Exception e) {
            log.error("取消订单失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "取消订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新订单状态
     */
    @PostMapping("/{orderId}/status")
    public Result<Boolean> updateOrderStatus(
            @PathVariable String orderId,
            @RequestParam String status,
            @RequestParam String statusName) {
        try {
            log.info("更新订单状态请求: {}, 状态: {}, 状态名称: {}", orderId, status, statusName);
            boolean result = orderService.updateOrderStatus(orderId, status, statusName);
            if (result) {
                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(500, "更新订单状态失败");
            }
        } catch (Exception e) {
            log.error("更新订单状态失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "更新订单状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取订单统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getOrderStats() {
        try {
            log.info("获取订单统计信息请求");
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalCount", orderService.getOrderCount());
            stats.put("pendingCount", orderService.getOrderCountByStatus("pending"));
            stats.put("paidCount", orderService.getOrderCountByStatus("paid"));
            stats.put("activeCount", orderService.getOrderCountByStatus("active"));
            stats.put("canceledCount", orderService.getOrderCountByStatus("canceled"));
            
            return ResultUtils.success(stats);
        } catch (Exception e) {
            log.error("获取订单统计信息失败: {}", e.getMessage(), e);
            return ResultUtils.error(500, "获取订单统计信息失败: " + e.getMessage());
        }
    }
}
